package yang.yu.sunny.datamodel;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.dayatang.domain.AbstractEntity;
import yang.yu.sunny.domain.EntityNotFoundException;
import yang.yu.sunny.domain.PriceNotFoundException;
import yang.yu.sunny.domain.Product;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * 订单项目
 * Created by yyang on 16/3/15.
 */
@Entity
@Table(name = "order_items_data")
public class OrderItemData extends AbstractEntity {

    private Long orderId;

    private Long productId;

    private double unitPrice;

    private double quantity;

    private double totalPrice;

    private double discount;

    protected OrderItemData() {
    }

    public OrderItemData(Long orderId, Long productId, double quantity) {
        this(orderId, productId, quantity, 0);
    }

    public OrderItemData(Long orderId, Long productId, double quantity, double discount) {
        this.orderId = orderId;
        this.productId = productId;
        this.quantity = quantity;
        Product product = Product.get(productId).orElseThrow(EntityNotFoundException::new);
        this.unitPrice = product.getCurrentUnitPrice().orElseThrow(PriceNotFoundException::new);
        this.totalPrice = unitPrice * quantity * (1 - discount);
    }

    public Long getOrderId() {
        return orderId;
    }

    public void setOrderId(Long orderId) {
        this.orderId = orderId;
    }

    public Long getProductId() {
        return productId;
    }

    public void setProductId(Long productId) {
        this.productId = productId;
    }

    public double getUnitPrice() {
        return unitPrice;
    }

    public void setUnitPrice(double unitPrice) {
        this.unitPrice = unitPrice;
    }

    public double getQuantity() {
        return quantity;
    }

    public void setQuantity(double quantity) {
        this.quantity = quantity;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public double getDiscount() {
        return discount;
    }

    public void setDiscount(double discount) {
        this.discount = discount;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }

        if (!(o instanceof OrderItemData)) {
            return false;
        }

        OrderItemData that = (OrderItemData) o;

        return new EqualsBuilder()
                .append(getOrderId(), that.getOrderId())
                .append(getProductId(), that.getProductId())
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(getOrderId())
                .append(getProductId())
                .toHashCode();
    }
}
